package org.bjf.modules.wechat.controller;

import org.bjf.modules.sys.bean.SysUser;
import org.bjf.modules.sys.query.SysUserQuery;
import org.bjf.modules.sys.service.SysUserService;
import org.bjf.modules.wechat.config.WechatConfig;
import org.bjf.modules.wechat.gateway.WxGateway;
import org.bjf.modules.wechat.gateway.WxScopeEnum;
import org.bjf.modules.wechat.gateway.WxTokenInfoDO;
import org.bjf.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

/**
 * 微信开放平台应用扫码登录
 * 官方文档：https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
 */
@Controller
@RequestMapping("/wechat")
public class WxLoginController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private WxGateway wxGateway;

    //用户授权同意后回调的地址
    @Value("${wechat.mp-login-redirecturl:http://localhost:9095/wechat/qrUserInfo}")
    private String redirectUrL;

    /**
     * 1.返回微信二维码页面
     */
    @GetMapping("/qrAuthorize")
    public String qrAuthorize() {
        return "redirect:" + wxGateway.getOpenAuthCodeUrl(WechatConfig.openAppId, WxScopeEnum.SNSAPI_BASE, redirectUrL);
    }

    /**
     * 2.用户授权同意后回调的地址，通过code取用户信息
     */
    @GetMapping("/qrUserInfo")
    public String qrUserInfo(@RequestParam("code") String code, String state) {
        // 校验是否合法或者过期
        TokenUtil.parseJwtToken(state);
        WxTokenInfoDO tokenInfoDO = wxGateway.getTokenInfoByAuthCode(code, WechatConfig.openAppId, WechatConfig.openAppSecret);

        return "redirect:/wechat/login?openid=" + tokenInfoDO.getOpenid();
    }

    /**
     * openid 登录
     */
    @GetMapping("/login")
    public String login(@RequestParam("openid") String openid) {
        SysUser user = sysUserService.getOne(new SysUserQuery().setUsername(openid));
        if (user == null) {
            // 去注册页面
            return "redirect:/register?openid=" + openid;
        }
        // doLogin后去首页
        return "/home";
    }

}
